package leetcode;

import java.util.ArrayList;

public class Convert {
    public static void main(String[] args) {
        String paypalishiring = convert2("PAYPALISA", 3);
        System.out.println(paypalishiring);
    }
    public static String convert(String s, int numRows) {
        int n = s.length(),r = numRows;
        if (r ==1 || r > n) return s;
        int t = 2*r-2;//周期
        int c = (n/t + 1)*(r-1);//每个周期占r-1列 c需要的二维数组列数 多加一个周期防越界
        char[][] chars = new char[r][c];
        //当 i%t < r-1时向下移动，否则向右上移动
        for (int i = 0,line = 0,row = 0;i<n;i++){
            chars[line][row] = s.charAt(i);
            if (i%t < r-1){
                line++;
            }else {
                line--;
                row++;
            }
        }
        //StringBuffer线程安全
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0;i<r;i++){
            for (int j = 0;j<c;j++){
                if (chars[i][j]!=0){
                    stringBuffer.append(chars[i][j]);
                }
            }
        }
        return stringBuffer.toString();
    }
    public static String convert1(String s, int numRows) {
        int n = s.length(),r = numRows;
        if (r ==1 || r > n) return s;
        int t = 2*r-2;//周期
        //优化成成一个链表数组,压缩空间
        StringBuffer[] buffer = new StringBuffer[r];
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = new StringBuffer();
        }
        
        for (int i = 0,x = 0;i<n;i++){
            buffer[x].append(s.charAt(i));
            if (i%t < r-1){
                x++;
            }else {
                x--;
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (StringBuffer stringBuffer1: buffer){
            stringBuffer.append(stringBuffer1);
        }
        return stringBuffer.toString();
    }

    public static String convert2(String s, int numRows) {
        if (numRows == 1) return s;

        int step = numRows * 2 - 2; // 间距
        int index = 0;// 记录s的下标
        int len = s.length();
        int add = 0; // 真实的间距
        StringBuffer ret = new StringBuffer();
        for (int i = 0; i < numRows; i++) // i表示行号
        {
            index = i;
            add = i * 2;
            while (index < len)//超出字符串长度计算下一层
            {
                ret.append(s.charAt(index)); // 当前行的第一个字母
                add = step - add;// 第一次间距是step -2*i，第二次是2*i,
                index += (i == 0 || i == numRows-1) ? step : add; // 0行和最后一行使用step间距，其余使用add间距
            }
        }
        return ret.toString();
    }
}
